import env from "@/env"
import { router } from "@/router"
import store from "@/store/index.js"

const baseUrl = env.AUTH_URL

// 接口统一处理
const request = (data, re = true) => {
	// 获取到token后请求头中携带token
	const httpHeader = {
		"Content-Type": 'application/json',
		"Authorization": store.getters.token,
	}
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + data.url,
			method: data.method || 'GET',
			timeout: 8000,
			header: httpHeader,
			data: data.params,
			success: res => {
				if (res.statusCode === 200) {
					resolve(res.data)
				} else {
					if (process.env.NODE_ENV === 'development') {
						if (res.data && typeof res.data === 'string') {
							uni.showToast({
								title: res.data,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: 'StatusCode错误url:' + data.url,
								icon: 'none'
							})
						}
					} else {
						if (typeof res.data === 'string') {
							uni.showToast({
								title: res,
								icon: 'none'
							})
						} else if (typeof res.data.msg === 'string') {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: "网络错误",
								icon: 'none'
							})
						}
					}
					reject({
						data: res.data,
						errMsg: 'errStatusCode' + res.statusCode
					})
				}
			},
			fail: err => {
				console.log('err', err)
				reject({
					data: err,
					errMsg: '请求失败'
				});
				uni.showToast({
					title: '请求失败' + data.url,
					icon: 'none'
				})
			}
		})
	})
}

export default request